package com.m3839.sdk.common.core;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import com.m3839.sdk.common.util.AppUtils;

/**
 * @author ChenBaoyang
 * @description: SDKLifecycle
 * @date 2021/11/27 15:41
 */
public class SDKLifecycle {

    private final Application application;
    private ApplicationStateCallback callback;

    private static SDKLifecycle lifecycle;

    private boolean isFromBackGround;

    private Activity currentActivity;

    public static void install(Context context, ApplicationStateCallback callback) {
        Application application = (Application) context.getApplicationContext();
        lifecycle = new SDKLifecycle(application, callback);

        application.registerActivityLifecycleCallbacks(lifecycle.lifecycleCallbacks);
    }

    private final Application.ActivityLifecycleCallbacks lifecycleCallbacks =
            new Application.ActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

                }

                @Override
                public void onActivityStarted(Activity activity) {
                    if (isFromBackGround) {
                        callback.onActive();
                        isFromBackGround = false;
                    }
                }

                @Override
                public void onActivityResumed(Activity activity) {
                    currentActivity = activity;
                }

                @Override
                public void onActivityPaused(Activity activity) {

                }

                @Override
                public void onActivityStopped(Activity activity) {
                    if (AppUtils.isAppIsInBackground(activity)) {
                        isFromBackGround = true;
                        callback.onInactive();
                    }
                }

                @Override
                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

                }

                @Override public void onActivityDestroyed(Activity activity) {

                }
            };



    private SDKLifecycle(Application application, ApplicationStateCallback callback) {
        this.application = application;
        this.callback = callback;
    }

    public static void unInstall() {
        lifecycle.internalUninstall();
    }

    private void internalUninstall() {
        application.unregisterActivityLifecycleCallbacks(lifecycleCallbacks);
    }

    public Activity getCurrentActivity() {
        return currentActivity;
    }

    public interface ApplicationStateCallback {
        /**
         * 应用活跃状态（在前台）
         */
        void onActive();

        /**
         * 应用处理不活跃状态（在后台）
         */
        void onInactive();

    }
}
